package com.gucheng.aigc.retry;

import com.github.rholder.retry.*;
import com.google.common.base.Predicates;

import com.gucheng.aigc.manager.ImageManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 *
 * @Date 2024/4/8 21:07
 * @注释
 */
@Component
@Slf4j
public class ImageRetrying {
    @Resource
    private ImageManager imageManager;


    public String retryDoChart(String userInput) {
        Callable<String> callable = () -> imageManager.generateImage(userInput);

        // 定义重试器
        Retryer<String> retryer = RetryerBuilder.<String>newBuilder()
                .retryIfResult(Predicates.isNull()) // 如果结果为空则重试
                .retryIfExceptionOfType(IOException.class) // 发生IO异常则重试
                .retryIfRuntimeException() // 发生运行时异常则重试
                .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS)) // 固定等待3秒
                .withStopStrategy(StopStrategies.stopAfterAttempt(3)) // 允许执行3次（首次执行 + 最多重试2次）
                .build();

        try {
            return retryer.call(callable); // 执行
        } catch (RetryException | ExecutionException e) { // 重试次数超过阈值或被强制中断
            // 处理异常
            e.printStackTrace();
            return null;
        }
    }
}

